package com.yunmang.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.google.gson.Gson;
import com.yunmang.R;
import com.yunmang.app.AppConstant;
import com.yunmang.entity.MemberBean;
import com.yunmang.entity.NameBean;
import com.yunmang.entity.OpenTicketResultBean;
import com.yunmang.entity.ParameterEntity.OpenTicketBean;
import com.yunmang.entity.event.EndEvent;
import com.yunmang.http.HttpUtils;
import com.yunmang.utils.ChangeRmb;
import com.yunmang.utils.CommonUtils;
import com.yunmang.utils.DateUtil;
import com.yunmang.utils.FormatUtils;
import com.yunmang.utils.SharedPreferencesUtils;
import com.yunmang.view.StatusPrintBox;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import HPRTAndroidSDK.HPRTPrinterHelper;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Subscriber;
import zpSDK.zpSDK.zpSDK;

/**
 * Created by Administrator on 2017/5/3.
 */
public class kaipiaoActivity extends BaseActivity implements OnItemClickListener {
    @InjectView(R.id.toolbar)
    Toolbar mToolbar;
    @InjectView(R.id.et_date)
    TextView etDate;
    @InjectView(R.id.tv_delivery_station)
    TextView tvDeliveryStation;
    @InjectView(R.id.et_zd_station)
    TextView dzStation;
    @InjectView(R.id.et_zz_station)
    EditText etZzStation;
    @InjectView(R.id.et_card_number)
    EditText etCardNumber;
    @InjectView(R.id.et_sh_number)
    EditText etShNumber;
    @InjectView(R.id.et_sh_name)
    EditText etShName;
    @InjectView(R.id.et_fh_number)
    EditText etFhNumber;
    @InjectView(R.id.et_fh_name)
    EditText etFhName;
    @InjectView(R.id.et_sh_address)
    EditText etShAddress;
    @InjectView(R.id.et_cargo_name)
    EditText etCargoName;
    @InjectView(R.id.spinner_pack)
    TextView spinnerPack;
    @InjectView(R.id.cargo_number)
    EditText cargoNumber;
    @InjectView(R.id.et_cargo_freight)
    EditText etCargoFreight;
    @InjectView(R.id.et_collect_money)
    EditText etCollectMoney;
    @InjectView(R.id.et_zz_money)
    EditText etZzMoney;
    @InjectView(R.id.et_cargo_quality)
    EditText etCargoQuality;
    @InjectView(R.id.et_cargo_bulk)
    EditText etCargoBulk;
    @InjectView(R.id.spinner_count_style)
    TextView countStyle;
    @InjectView(R.id.et_rebates)
    EditText etRebates;
    @InjectView(R.id.et_delivery_charge)
    EditText etDeliveryCharge;
    @InjectView(R.id.et_insure_fare)
    EditText etInsureFare;
    @InjectView(R.id.rg_delivery_style)
    RadioGroup rgDeliveryStyle;
    @InjectView(R.id.rg_is_receipt)
    RadioGroup rgIsReceipt;
    @InjectView(R.id.et_remark)
    EditText etRemark;
    @InjectView(R.id.et_note_number)
    EditText etNoteNumber;
    @InjectView(R.id.cb_hkyf)
    CheckBox cbHkyf;
    @InjectView(R.id.cb_dyyd)
    CheckBox cbDyyd;
    @InjectView(R.id.cb_dybq)
    CheckBox cbDybq;
    @InjectView(R.id.cb_dnbq)
    CheckBox cbDnbq;
    @InjectView(R.id.cb_remind_shr)
    CheckBox cbRemindShr;
    @InjectView(R.id.cb_fkpz)
    CheckBox cbFkpz;
    @InjectView(R.id.btn_save)
    Button btnSave;
    @InjectView(R.id.save_noprint)
    Button btnSaveNoPrint;
    @InjectView(R.id.rb_ziti)
    RadioButton rb_ziti;
    @InjectView(R.id.rb_sh)
    RadioButton rb_sh;
    @InjectView(R.id.et_hdbh)
    EditText etHdbh;
    @InjectView(R.id.cb_hdbh)
    CheckBox cbHdbh;
    @InjectView(R.id.iv_card)
    TextView ivCard;
    @InjectView(R.id.et_baoe)
    EditText etBaoe;
    private int endId, memberid;//到站id ,会员id
    private Subscriber subscriber;
    private BluetoothAdapter myBluetoothAdapter;
    private String[] packArray, balanceArray;
    private OpenTicketBean openTicketBean;
    StatusPrintBox statusBox;
    private AlertView packAlertView, balanceAlertView;

    private String songhuoStyle = "自提";
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    public static HPRTPrinterHelper HPRTPrinter = new HPRTPrinterHelper();
    private boolean isTagprint = true, isReceiptPrint = true;//是否打印标签
    private String receipt_printer_style, tag_printer_style;//打印机类型
    private boolean connect_status;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_open_order;
    }

    @Override
    public void initView() {
        ButterKnife.inject(this);
        //注册
        EventBus.getDefault().register(this);
        initToolbar();
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        etCardNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {

                } else {
                    String card = etCardNumber.getText().toString().trim();
                    if (!TextUtils.isEmpty(card)) {
                        getMemberInfo(card);
                    }
                }
            }
        });
        etFhNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {

                } else {
                    String shipper = etFhNumber.getText().toString().trim();
                    if (!TextUtils.isEmpty(shipper)) {
                        getShipperName(shipper);
                    }
                }
            }
        });
        etShNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {

                } else {
                    String consignee = etShNumber.getText().toString().trim();
                    if (!TextUtils.isEmpty(consignee)) {
                        getConsigneeName(consignee);

                    }
                }
            }
        });
        dzStation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(context, SearchEndActivity.class));
            }
        });
        //包装
        packArray = getResources().getStringArray(R.array.pack);
        spinnerPack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fillPack(packArray);
            }
        });
        //结算方式
        balanceArray = getResources().getStringArray(R.array.balance);
        countStyle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fillBalanceStyle(balanceArray);
            }
        });
        cargoNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                etNoteNumber.setText(charSequence.toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        //手工单号
        cbHdbh.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    etHdbh.setEnabled(true);
                    showToast("可以填写手工单");
                } else {
                    etHdbh.setEnabled(false);
                    etHdbh.setText("");
                    showToast("取消填写手工单");
                }
            }
        });
    }

    private void initToolbar() {
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("运单受理");
        mToolbar.setNavigationIcon(R.mipmap.ic_back);
    }

    private void fillBalanceStyle(String[] balanceArray) {
        balanceAlertView = new AlertView(null, null, null, null, balanceArray, this, AlertView.Style.Alert, this);
        balanceAlertView.show();
    }

    private void fillPack(String[] stringArray) {
        packAlertView = new AlertView(null, null, null, null, stringArray, this, AlertView.Style.Alert, this);
        packAlertView.show();
    }

    @Override
    public void initData() {
        etDate.setText(DateUtil.date2string(new Date(), DateUtil.YYYY_MM_DD));
        tvDeliveryStation.setText(AppConstant.orgInfo.getName());
    }

    /**
     * 获取收货人姓名
     *
     * @param consigneeName
     */
    private void getConsigneeName(String consigneeName) {
        subscriber = new Subscriber<NameBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                showToast("onError" + e.toString());
            }

            @Override
            public void onNext(NameBean nameBean) {
//                hideWaitingDialog();
                if (nameBean.getCode() == 200) {
                    if (nameBean.getModel() != null) {
                        etShName.setText(nameBean.getModel());
                    } else {
                    }
                } else {
                }
            }

        };
        HttpUtils.getInstance().getConsignee(subscriber, consigneeName);
    }

    /**
     * 获取收货人姓名
     *
     * @param shipperNumber
     */
    private void getShipperName(String shipperNumber) {
//        showWaitingDialog("正在获取……");
        subscriber = new Subscriber<NameBean>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                showToast("onError" + e.toString());
            }

            @Override
            public void onNext(NameBean nameBean) {
                if (nameBean.getCode() == 200) {
                    if (!TextUtils.isEmpty(nameBean.getModel())) {
                        etFhName.setText(nameBean.getModel());
                    } else {
                    }
                } else {
                }
            }
        };
        HttpUtils.getInstance().getshipper(subscriber, shipperNumber);
    }

    /**
     * 获取会员卡信息
     *
     * @param code 10014
     */
    private void getMemberInfo(String code) {
        showWaitingDialog("正在获取……");
        subscriber = new Subscriber<MemberBean>() {

            @Override
            public void onCompleted() {
                hideWaitingDialog();
            }

            @Override
            public void onError(Throwable e) {
                hideWaitingDialog();
                clearEditInfo(etCardNumber);
                showToast("onError" + e.toString());
            }

            @Override
            public void onNext(MemberBean memberBean) {
                hideWaitingDialog();
                if (memberBean.getCode() == 200) {
                    if (memberBean.getModel() != null) {
                        etFhNumber.setText(memberBean.getModel().getTelephone());
                        etFhName.setText(memberBean.getModel().getName());
                        memberid = memberBean.getModel().getId();
                    } else {
                        clearEditInfo(etCardNumber);
                        showToast("暂无该卡号");
                    }
                } else {
                    clearEditInfo(etCardNumber);
                    showToast(memberBean.getMessage().toString());
                }
            }
        };
        HttpUtils.getInstance().getMemberInfo(subscriber, code);
    }


    /**
     * 使用onEventMainThread来接收事件，那么不论分发事件在哪个线程运行，接收事件永远在UI线程执行
     * 可以用来更新UI
     *
     * @param event
     */
    public void onEventMainThread(EndEvent event) {
        endId = event.getId();
        dzStation.setText(event.getName());
    }

    @OnClick({R.id.btn_save, R.id.save_noprint})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_save:
                showWaitingDialog("正在上传中……");
                btnSave.setEnabled(false);
                checkPageInfo(true);
                break;
            case R.id.save_noprint:
                showWaitingDialog("正在上传中……");
                btnSaveNoPrint.setEnabled(false);
                checkPageInfo(false);
                break;
        }
    }


    private void checkPageInfo(boolean b) {
        if (etCardNumber.hasFocus()) {//如果有焦点
            String cd = etCardNumber.getText().toString().trim();
            if (!TextUtils.isEmpty(cd)) {
                getMemberInfo(cd);
            }
        }
        if (CommonUtils.checkTextIsEmpty(dzStation)) {
            showToast("直达站不能为空！");
            onActionDone();
            return;
        }
        if (CommonUtils.checkTextIsEmpty(etShNumber)) {
            showToast("收货方手机不能为空！");
            onActionDone();
            return;
        }
        if (CommonUtils.checkTextIsEmpty(etShName)) {
            showToast("收货方姓名不能为空！");
            onActionDone();
            return;
        }
        if (CommonUtils.checkTextIsEmpty(etFhNumber)) {
            showToast("发货方手机不能为空！");
            onActionDone();
            return;
        }
        if (CommonUtils.checkTextIsEmpty(etFhName)) {
            showToast("发货方姓名不能为空！");
            onActionDone();
            return;
        }
        if (CommonUtils.checkTextIsEmpty(etCargoName)) {
            showToast("货物名称不能为空！");
            onActionDone();
            return;
        }
        if (CommonUtils.checkTextIsEmpty(cargoNumber)) {
            showToast("货物数量不能为空！");
            onActionDone();
            return;
        }
        if (CommonUtils.checkTextIsEmpty(etCargoFreight)) {
            showToast("货物运费不能为空！");
            onActionDone();
            return;
        }
        //送货方式
        if (rb_sh.isChecked()) {
            songhuoStyle = "送货";
        } else {
            songhuoStyle = "自提";
        }
        //hdbh
        String hdbh = CommonUtils.getTextViewValue(etHdbh);
//        if(!TextUtils.isEmpty(hdbh)){
//            if(hdbh.length()<12){
//                showToast("手工单号必须大于等于12位");
//                onActionDone();
//                return;
//            }
//        }
        int UserId = Integer.parseInt(AppConstant.userid); // 用户ID
        int DepartId = AppConstant.orgInfo.getId(); // 起站ID
        int EndDepartId = endId; // 到站ID
        String TransferAddress = etZzStation.getText().toString().trim();
        String MemberNo = etCardNumber.getText().toString().trim();
        int MemberId = memberid;//会员id，可为空
        String ShipperPhone = CommonUtils.getTextViewValue(etFhNumber);
        String Shipper = CommonUtils.getTextViewValue(etFhName);
        String ConsigneePhone = CommonUtils.getTextViewValue(etShNumber);
        String Consignee = CommonUtils.getTextViewValue(etShName);
        String ConsigneeAddress = etShAddress.getText().toString().trim();//收货人详细地址，可为空
        String GoodsName = etCargoName.getText().toString().trim();
        int Numbers = CommonUtils.ChangeString2Int(cargoNumber);
        String Pack = spinnerPack.getText().toString().trim();//包装
        int Cubage = CommonUtils.ChangeString2Int(etCargoBulk);//体积
        int Weight = CommonUtils.ChangeString2Int(etCargoQuality);//重量
        int PremiumAmount = CommonUtils.ChangeString2Int(etBaoe);//保额
        int TransportCost = CommonUtils.ChangeString2Int(etCargoFreight); // 运费
        int BalanceMethod = CommonUtils.getBalanceMethod(CommonUtils.getTextViewValue(countStyle)); // 结算方式
        int GoodsCost = CommonUtils.ChangeString2Int(etCollectMoney); // 货款
        int TransferCost = CommonUtils.ChangeString2Int(etZzMoney); // 中转费
        int DeliveryCost = CommonUtils.ChangeString2Int(etDeliveryCharge); // 送货费
        String TakeMethod = songhuoStyle; //送货方式

        int DeliveryProofCount = 0;// 回单数量,没有传0
        String Notes = etRemark.getText().toString().trim();//备注,可为空
        openTicketBean = new OpenTicketBean();
        openTicketBean.setHdbh(hdbh);
        openTicketBean.setUserId(UserId);
        openTicketBean.setDepartId(DepartId);
        openTicketBean.setEndDepartId(EndDepartId);
        openTicketBean.setTransferAddress(TransferAddress);
        openTicketBean.setMemberNo(MemberNo);
        openTicketBean.setMemberId(MemberId);
        openTicketBean.setShipperPhone(ShipperPhone);
        openTicketBean.setShipper(Shipper);
        openTicketBean.setConsigneePhone(ConsigneePhone);
        openTicketBean.setConsignee(Consignee);
        openTicketBean.setConsigneeAddress(ConsigneeAddress);
        openTicketBean.setTakeMethod(songhuoStyle);
        OpenTicketBean.GoodsListEntity goodsListEntity = new OpenTicketBean.GoodsListEntity();
        goodsListEntity.setGoodsName(GoodsName);
        goodsListEntity.setNumbers(Numbers);
        goodsListEntity.setPack(Pack);
        goodsListEntity.setCubage(Cubage);
        goodsListEntity.setWeight(Weight);
        goodsListEntity.setPremiumAmount(PremiumAmount);
        List<OpenTicketBean.GoodsListEntity> list = new ArrayList<>();
        list.add(goodsListEntity);
        openTicketBean.setGoodsList(list);
        openTicketBean.setTransportCost(TransportCost);
        openTicketBean.setBalanceMethod(BalanceMethod);
        openTicketBean.setGoodsCost(GoodsCost);
        openTicketBean.setTransferCost(TransferCost);
        openTicketBean.setDeliveryCost(DeliveryCost);
        openTicketBean.setTakeMethod(TakeMethod);
        openTicketBean.setDeliveryProofCount(DeliveryProofCount);
        openTicketBean.setNotes(Notes);
        Gson gson = new Gson();
        String inJson = gson.toJson(openTicketBean);
        isReceiptPrint = cbDyyd.isChecked();
        isTagprint = cbDybq.isChecked();
        printKaipiao(inJson, b);
    }

    /**
     * 只有设置连接正常，才去访问接口，调用接口成功之后才去打印
     *
     * @param inJson
     */
    private void save(final String inJson) {
        subscriber = new Subscriber<OpenTicketResultBean>() {
            @Override
            public void onCompleted() {
                onActionDone();
            }

            @Override
            public void onError(Throwable e) {
                onActionDone();
                Log.i("LoginActivity", e.toString());
                Toast.makeText(context, "onError" + e.toString(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNext(final OpenTicketResultBean openTicketResultBean) {
                onActionDone();
                Log.e("data", inJson);
                if (openTicketResultBean.getCode() == 200) {
                    showToast("保存成功");
                    // TODO: 执行打印
                    if (isReceiptPrint) {
                        if (receipt_printer_style.equals(AppConstant.receipt_name)) {
                            actionPrintByZhiKe(openTicketResultBean.getModel());
                            zpSDK.zp_close();
                        }
                    }
                    if (isTagprint) {
                        if (tag_printer_style.equals(AppConstant.tag_name)) {
                            actionTagByHanYin(openTicketResultBean.getModel());
                        }
                    }
//                    if (0 != SharedPreferencesUtils.getParameter(context,"SelectedTagMac").length()) {
//                        statusBox = new StatusPrintBox(context,btnSave);
//                        String SelectedTagAddress = SharedPreferencesUtils.getParameter(context,"SelectedTagMac");
//                        Tag(SelectedTagAddress,openTicketResultBean.getModel());
//                    }else{
//                        showToast("请选择标签打印机");
//                        zpSDK.zp_close();
//                    }

//                    if (isTagprint) {
//                        //执行打印标签，用汉印打印机
//                        System.out.println("设备名称为："+printer_style);
//                        if(printer_style.equals("HM-T300")){//如果之前连接过蓝牙，进来自动连接
//                            new Handler().post(new Runnable() {
//                                @Override
//                                public void run() {
//                                    if(!HPRTPrinterHelper.IsOpened()){
//                                        tryconnect(openTicketResultBean.getModel());
//                                    }else{
//                                        PrintSampleReceipt(openTicketResultBean.getModel());
//                                    }
//                                }
//                            });
//                        }
//                    }
                    deleteOrderInformation();
                } else if (openTicketResultBean.getCode() == 300) {
                    zpSDK.zp_close();
                    showToast(openTicketResultBean.getMessage());
                } else {
                    zpSDK.zp_close();
                    showToast("数据错误！");
                }
            }
        };
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), inJson);
        HttpUtils.getInstance().save(subscriber, body);
    }

    private void actionTagByHanYin(final String model) {
        if (!HPRTPrinterHelper.IsOpened()) {
            tryconnect(model);
        } else {
            PrintSampleReceipt(model);
        }
//        new Handler().post(new Runnable() {
//            @Override
//            public void run() {
//                if(!HPRTPrinterHelper.IsOpened()){
//                    tryconnect(model);
//                }else{
//                    PrintSampleReceipt(model);
//                }
//            }
//        });
    }

    private void actionPrintByZhiKe(final String model) {
        statusBox = new StatusPrintBox(context, btnSave);
        final String SelectedPrintAddress = SharedPreferencesUtils.getParameter(context, "SelectedPrintMac");
        if (OpenPrinter(SharedPreferencesUtils.getParameter(this, "SelectedPrintMac")))
            Print(SelectedPrintAddress, model);
//        new Handler().post(new Runnable() {
//            @Override
//            public void run() {
//                Print(SelectedPrintAddress,model);
//            }
//        });


    }

    private void saveNotprint(final String inJson) {
        subscriber = new Subscriber<OpenTicketResultBean>() {
            @Override
            public void onCompleted() {
                onActionDone();
            }

            @Override
            public void onError(Throwable e) {
                onActionDone();
                Log.i("LoginActivity", e.toString());
                Toast.makeText(context, "onError" + e.toString(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNext(OpenTicketResultBean openTicketResultBean) {
                onActionDone();
                Log.e("data", inJson);
                if (openTicketResultBean.getCode() == 200) {
                    showAlertDialog("开票成功", "票号:" + openTicketResultBean.getModel() + "请在运单查询进行补打");
                    //要提示用户开票成功
                    deleteOrderInformation();
                } else if (openTicketResultBean.getCode() == 300) {
                    showAlertDialog("保存失败", openTicketResultBean.getMessage());
                } else {
                    showAlertDialog("保存失败", "数据错误");
                }
            }
        };
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), inJson);
        HttpUtils.getInstance().save(subscriber, body);
    }

    /**
     * true 表示要打出来票据
     * false 表示不出票只保存
     *
     * @param b
     */
    private void printKaipiao(String inJson, boolean b) {
        if (b) {//需要对打印机类型做区分
            if (isReceiptPrint) {
                if (0 == SharedPreferencesUtils.getParameter(this, "SelectedPrintMac").length()) {
                    showToast("请选择小票打印机");
                    onActionDone();
                    return;
                }
            }
            if (isTagprint) {
                if (0 == SharedPreferencesUtils.getParameter(this, "SelectedTagMac").length()) {
                    showToast("请选择标签打印机");
                    onActionDone();
                    return;
                }
            }
            tag_printer_style = SharedPreferencesUtils.getParameter(context, "selectedTagName");
            receipt_printer_style = SharedPreferencesUtils.getParameter(context, "selectedPrintName");
            save(inJson);
//            if (OpenPrinter(SharedPreferencesUtils.getParameter(this, "SelectedPrintMac"))) {
//                save(inJson);
//            } else {//当与蓝牙设备连接有问题
//                onActionDone();
//            }

        } else {
            saveNotprint(inJson);
        }
    }

    /**
     * 访问结束，需要置空
     */
    private void onActionDone() {
        hideWaitingDialog();
        btnSave.setEnabled(true);
        btnSaveNoPrint.setEnabled(true);
    }

    /**
     * 删除开票信息
     */
    private void deleteOrderInformation() {
        etZzStation.setText("");
        etCardNumber.setText("");
        etShNumber.setText("");
        etShName.setText("");
        etFhNumber.setText("");
        etFhName.setText("");
        etShAddress.setText("");
        etCargoName.setText("");
        cargoNumber.setText("");
        etCargoFreight.setText("");
        etCollectMoney.setText("");
        etZzMoney.setText("");
        etCargoQuality.setText("");
        etCargoBulk.setText("");
        etNoteNumber.setText("");
        etInsureFare.setText("");
        etDeliveryCharge.setText("");
        etRemark.setText("");
    }

    /**
     * 执行打印
     *
     * @param BDAddress
     * @param hdbh
     */
    public void Print(String BDAddress, String hdbh) {
        statusBox.Show("正在打印小票...");
        if (!zpSDK.zp_page_create(80, 80)) {
            Toast.makeText(this, "创建打印页面失败", Toast.LENGTH_LONG).show();
            statusBox.Close();
            return;
        }
        zpSDK.TextPosWinStyle = false;
        zpSDK.zp_page_clear();
        zpSDK.zp_draw_text_ex(26, 13, "", "Arial", 6, 0,
                false, false, false);
        zpSDK.zp_draw_barcode(18, 16, hdbh,
                zpSDK.BARCODE_TYPE.BARCODE_CODE128, 10, 3, 0); // /////////////////////下面全是横线///////////////////////////////////
        zpSDK.zp_draw_text_ex(24, 30, hdbh, "Arial", 4, 0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 25 + 5 + 5, "发货单号：" + hdbh, "Arial", 4, 0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 25 + 5 + 5 + 5, "发货日期：" + DateUtil.date2string(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS),
                "Arial", 4, 0, false, false, false);

        zpSDK.zp_draw_line(1, 41 + 1, 80, 41 + 1, 2); // 第一条线
        zpSDK.zp_draw_text_ex(1, 46, "起站：" + tvDeliveryStation.getText().toString().trim(), "Arial", 3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(40, 46, "到站：" + dzStation.getText().toString(), "Arial", 3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 49.5, "客户卡号：" + openTicketBean.getMemberNo(), "Arial", 3, 0,
                false, false, false);
        zpSDK.zp_draw_text_ex(40, 49.5, "中转至：" + openTicketBean.getTransferAddress(), "Arial", 3, 0,
                false, false, false);
        zpSDK.zp_draw_text_ex(1, 53, "发货人：" + openTicketBean.getShipper(), "Arial", 3, 0,
                false, false, false);
        zpSDK.zp_draw_text_ex(40, 53, "" + openTicketBean.getShipperPhone(), "Arial", 3, 0,
                false, false, false);
        zpSDK.zp_draw_text_ex(1, 56.5, "收货人：" + openTicketBean.getConsignee(), "Arial", 3,
                0, false, false, false);
        zpSDK.zp_draw_text_ex(40, 56.5, "" + openTicketBean.getConsigneePhone(), "Arial", 3, 0,
                false, false, false);
        zpSDK.zp_draw_line(1, 59, 80, 58 + 1, 2); // 第二条线
        zpSDK.zp_draw_text_ex(1, 63, "货物名称：" + openTicketBean.getGoodsList().get(0).getGoodsName(), "Arial", 3, 0,
                false, false, false);
        zpSDK.zp_draw_text_ex(40, 63, "包装：" + openTicketBean.getGoodsList().get(0).getPack(), "Arial", 3, 0,
                false, false, false);
        zpSDK.zp_draw_text_ex(1, 66.5, "数量：" + openTicketBean.getGoodsList().get(0).getNumbers(), "Arial", 3, 0,
                false, false, false);
        zpSDK.zp_draw_text_ex(40, 66.5, "运费：" + openTicketBean.getTransportCost(), "Arial", 3, 0,
                false, false, false);
        zpSDK.zp_draw_text_ex(1, 70, "送货费：" + openTicketBean.getDeliveryCost(), "Arial", 3, 0,
                false, false, false);
        zpSDK.zp_draw_text_ex(40, 70, "中转费：" + openTicketBean.getTransferCost(), "Arial", 3,
                0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 73.5, "保费：", "Arial", 3, 0,
                false, false, false);
        zpSDK.zp_draw_text_ex(1, 73.5 + 3.5, "备注：" + openTicketBean.getNotes(), "Arial", 3,
                0, false, false, false);
        Log.e("res", "执行1");
        zpSDK.zp_draw_line(1, 76 + 3.5, 80, 76 + 3.5, 2); // 第三条线
        zpSDK.zp_draw_text_ex(1, 80 + 3.5, "付款方式：" + countStyle.getText().toString().trim(),
                "Arial", 3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(40, 80 + 3.5, "提货方式：" + openTicketBean.getTakeMethod(),
                "Arial", 3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(
                1,
                83.5 + 3.5,
                "运费合计：￥"
                        + String.valueOf(Integer.valueOf("1")
                        + Integer.valueOf("1")
                        + Integer.valueOf("1")), "Arial",
                3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(
                40,
                83.5 + 3.5,
                "", "Arial", 3, 0,
                false, false, false);
        zpSDK.zp_draw_text_ex(1, 88.5 + 3.5, "货款: ￥" + openTicketBean.getGoodsCost(), "Arial",
                5, 0, false, false, false);

        if ("".equals(ChangeRmb.toRMB(openTicketBean.getGoodsCost()))) {
            zpSDK.zp_draw_text_ex(1, 93.5 + 3.5, "货款大写: 零元整", "Arial", 5, 0, false, false, false);
        } else {
            zpSDK.zp_draw_text_ex(1, 93.5 + 3.5, "货款大写: " + ChangeRmb.toRMB(openTicketBean.getGoodsCost()),
                    "Arial", 5, 0, false, false, false);
        }
        zpSDK.zp_draw_line(1, 95.5 + 3.5, 80, 95.5 + 3.5, 2); // 第四条线
        zpSDK.zp_draw_text_ex(1, 99.5 + 3.5, "开票人：" + AppConstant.orgInfo.getName(), "Arial", 3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 103 + 3.5, "客服电话：" + "53666612 ；55180695； 89916652； ", "Arial",
                3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 103 + 7, "89916653 ", "Arial",
                3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 103 + 10.5, "投诉电话：" + "15238647899", "Arial",
                3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 117, "提货网点电话：",
                "Arial", 3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 120.5, "查货微信：" + "soft56", "Arial", 3, 0,
                false, false, false);
        zpSDK.zp_draw_text_ex(1, 124, "查货网址：" + "http://www.hncxwl.cn",
                "Arial", 3, 0, false, false, false);
        zpSDK.zp_draw_line(1, 126.5, 80, 126.5, 2); // 第三条线
        zpSDK.zp_draw_text_ex(1, 130, "温馨提示： ①易碎物品如瓷罐、玻璃、洁具等，公司",
                "Arial", 3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 133.5, "只负责丢失责任，不负责损坏责任②公司实施保价运",
                "Arial", 3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 137, "输制度，货物无代收无保价者，货物丢失损坏公司将", "Arial",
                3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 140.5, "按运费的1-5倍赔偿③原票返回货物，自通知之日起应",
                "Arial", 3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 144, "在三日内提取货物，逾期不提货者自通知之日起按照", "Arial",
                3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 147.5, "每天每件2元的标准收取仓管费④货物超过1年不结算",
                "Arial", 3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 151, "或不查询票据将自动作废⑤托运货物实行件收件交制，",
                "Arial", 3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 154.5, "以外包装完整为准不开箱验货，对包装内容以及包装",
                "Arial", 3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 158, "完好程度不承认担责任⑥货到十天不提货者，公司有", "Arial",
                3, 0, false, false, false);
        zpSDK.zp_draw_text_ex(1, 161.5, "权自动原票返回⑦此协议涂改无效。", "Arial", 3, 0, false,
                false, false);

        zpSDK.zp_draw_text_ex(1, 165,
                "【晶科软件】 http://www.jkcom.net ", "Arial", 3, 0,
                false, false, false);
        zpSDK.zp_draw_text_ex(1, 168.5, "查询货款·关注微信【晶科软件】", "Arial", 3, 0,
                true, false, false);

        zpSDK.zp_page_print(false);
        zpSDK.zp_printer_status_detect();
        zpSDK.zp_goto_mark_right(15);
        switch (zpSDK.zp_printer_status_get(8000)) {
            case 1:
                showToast("纸舱盖打开");
                break;
            case 2:
                showToast("打印机缺纸");
                break;
            case 4:
                showToast("打印机打印头过热");
                break;
            default:
                showToast("开票成功");
                break;
        }
        zpSDK.zp_page_free();
        statusBox.Close();

    }

    public void Tag(String BDAddress, String hdbh) {
        statusBox.Show("正在打印标签...");
        String num = CommonUtils.getTextViewValue(etNoteNumber);
        if (!OpenPrinter(BDAddress)) {
            statusBox.Close();
            return;
        }
        if (!zpSDK.zp_page_create(80, 44)) {
            Toast.makeText(this, "创建打印页面失败", Toast.LENGTH_LONG).show();
            statusBox.Close();
            return;
        }
        for (int i = 0; i < Integer.parseInt(num); i++) {
            Draw_Content(i + 1, hdbh);
            zpSDK.zp_page_print(false);
            zpSDK.zp_goto_mark_label(44);
            zpSDK.zp_printer_status_detect();
            if (zpSDK.zp_printer_status_get(8000) != 0) {
//                if (zpSDK.ErrorMessage, "打印失败") == 1) {
//                    i--;
//                    continue;
//                } else {
//                    statusBox.Close();
//                    zpSDK.zp_page_free();
//                    break;
//                }
            }
        }// for
        zpSDK.zp_page_free();
        zpSDK.zp_close();
        statusBox.Close();
    }

    public void Draw_Content(int num, String hdbh) {
        zpSDK.zp_page_clear();
        zpSDK.zp_draw_text_ex(2, 6, "", "Arial", 6, 0,
                false, false, false);
        zpSDK.zp_draw_text_ex(10, 15, hdbh + FormatUtils.generate(String.valueOf(num)), "Arial", 4, 0,
                false, false, false);
        zpSDK.zp_draw_barcode(3, 2, hdbh + FormatUtils.generate(String.valueOf(num)), zpSDK.BARCODE_TYPE.BARCODE_CODE128, 10,
                3, 0); // /////////////////////下面全是横线///////////////////////////////////

        if (!"".equals(openTicketBean.getTransferAddress().trim())) {
            String des = "";
            if (openTicketBean.getTransferAddress().trim().length() > 3) {
                des = openTicketBean.getTransferAddress().trim().substring(0, 3);
            } else {
                des = openTicketBean.getTransferAddress().trim();
            }
            zpSDK.zp_draw_text_ex(1, 21, "到站：" + CommonUtils.getTextViewValue(dzStation) + " 转 " + des + " " + "件",
                    "Arial", 6, 0, false, false, false);
        } else {
            zpSDK.zp_draw_text_ex(1, 21, "到站：" + CommonUtils.getTextViewValue(dzStation) + " " + "件", "Arial", 6, 0, false, false,
                    false);
        }
        zpSDK.zp_draw_text_ex(1, 27, "货    物：" + openTicketBean.getGoodsList().get(0).getGoodsName(), "Arial", 5, 0,
                false, false, false);
        zpSDK.zp_draw_text_ex(1, 33, "收货人：" + openTicketBean.getConsignee(), "Arial", 5, 0, false,
                false, false);
        zpSDK.zp_draw_text_ex(40, 33, "包装：" + openTicketBean.getGoodsList().get(0).getPack(), "Arial", 5, 0, false,
                false, false);
        zpSDK.zp_draw_text_ex(1, 39, "起    站：" + CommonUtils.getTextViewValue(tvDeliveryStation), "Arial", 5, 0, false, false, false);
    }

    public boolean OpenPrinter(String BDAddress) {
        if (BDAddress == "" || BDAddress == null) {
            Toast.makeText(this, "没有选择打印机", Toast.LENGTH_LONG).show();
            return false;
        }
        BluetoothDevice myDevice;
        myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (myBluetoothAdapter == null) {
            Toast.makeText(this, "读取蓝牙设备错误", Toast.LENGTH_LONG).show();
            return false;
        }
        myDevice = myBluetoothAdapter.getRemoteDevice(BDAddress);
        if (myDevice == null) {
            Toast.makeText(this, "读取蓝牙设备错误", Toast.LENGTH_LONG).show();
            return false;
        }
        if (zpSDK.zp_open(myBluetoothAdapter, myDevice) == false) {
            Toast.makeText(this, "与蓝牙设备建立连接失败", Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onItemClick(Object o, int position) {
        if (o == packAlertView && position != AlertView.CANCELPOSITION) {
            spinnerPack.setText(packArray[position]);
        } else if (o == balanceAlertView && position != AlertView.CANCELPOSITION) {
            countStyle.setText(balanceArray[position]);
        }
    }


    /**
     * 弹出对话框
     *
     * @param string
     */
    private void showAlertDialog(String hint, String string) {
        new AlertView(hint, string, null, new String[]{"确定"}, null, this, AlertView.Style.Alert, this).show();
    }


    private void tryconnect(String model) {
        boolean hasConnected = false;
        hasConnected = ConnectDevice();
        if (hasConnected) {
            DisConnect();
        }
        if (hasConnected) {
            showToast("连接成功");
            kaipiaoActivity.HPRTPrinter = new HPRTPrinterHelper(this, "HM-T300");
            try {
                if (HPRTPrinterHelper.PortOpen("Bluetooth," + SharedPreferencesUtils.getParameter(this, "SelectedTagMac")) == 0) {
                    PrintSampleReceipt(model);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            showToast("连接失败");
        }
    }

    private void PrintSampleReceipt(String hdbh) {
        try {
            if (!HPRTPrinterHelper.IsOpened()) {
                showToast("请进行蓝牙连接");
                return;
            }
            int sumNum = openTicketBean.getGoodsList().get(0).getNumbers();//总件数
            String tagnum = CommonUtils.getTextViewValue(etNoteNumber);
            if (!TextUtils.isEmpty(tagnum)) {
                sumNum = Integer.parseInt(tagnum);
                if (sumNum > 20) {
                    sumNum = 20;
                }
            }
            for (int i = 0; i <= sumNum; i++) {
                if (i == 0) {
                    printOrder(hdbh);
                } else {
                    HPRTPrinterHelper.printAreaSize("0", "200", "600", "450", "1");
                    HPRTPrinterHelper.LanguageEncode = "GBK";
                    HPRTPrinterHelper.Align(HPRTPrinterHelper.LEFT);
                    HPRTPrinterHelper.Barcode(HPRTPrinterHelper.BARCODE, HPRTPrinterHelper.code128, "2", "1", "65", "40", "40", true, "7", "0", "5", hdbh + FormatUtils.generate(String.valueOf(i)));
                    HPRTPrinterHelper.Line("10", "135", "600", "135", "2");
                    HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "9", "3", "20", "150", CommonUtils.getTextViewValue(tvDeliveryStation) + "-" + CommonUtils.getTextViewValue(dzStation));

                    HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "9", "3", "20", "210", "货名:" + openTicketBean.getGoodsList().get(0).getGoodsName());
                    HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "9", "3", "20", "280", "收货人:" + openTicketBean.getConsignee());
                    HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "9", "3", "20", "350", DateUtil.date2string(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                    HPRTPrinterHelper.Form();
//                    HPRTPrinterHelper.Print();
                    HPRTPrinterHelper.PrintData("POPRINT\r\n");
                }

            }
        } catch (Exception e) {
            Log.e("HPRTSDKSample", (new StringBuilder("Activity_Main --> PrintSampleReceipt ")).append(e.getMessage()).toString());
        }
    }

    private void printOrder(String hdbh) {
        HPRTPrinterHelper.printAreaSize("0", "200", "600", "450", "1");
        HPRTPrinterHelper.LanguageEncode = "GBK";
        HPRTPrinterHelper.Align(HPRTPrinterHelper.LEFT);
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "9", "3", "150", "5", AppConstant.companyName + "运单");
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "8", "0", "180", "55", hdbh);
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "8", "1", "10", "85", CommonUtils.getTextViewValue(tvDeliveryStation) + "-" + CommonUtils.getTextViewValue(dzStation) + "  " + openTicketBean.getGoodsList().get(0).getNumbers() + "件");
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "8", "1", "10", "135", "发货人:" + openTicketBean.getShipper() + "  " + openTicketBean.getShipperPhone());
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "8", "1", "10", "185", "收货人:" + openTicketBean.getConsignee() + "  " + openTicketBean.getConsigneePhone());
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "8", "1", "10", "230", "运费:" + openTicketBean.getTransportCost() + "  送货费：" + openTicketBean.getDeliveryCost() + "  中转费：" + openTicketBean.getTransferCost());
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "8", "1", "10", "280", "货款:" + openTicketBean.getGoodsCost());
        HPRTPrinterHelper.Text(HPRTPrinterHelper.TEXT, "8", "1", "10", "330", "时间：" + DateUtil.date2string(new Date(), DateUtil.YYYY_MM_DD_HH_MM_SS) + "  " + openTicketBean.getTakeMethod() + "  " + CommonUtils.getNamebyBalance(openTicketBean.getBalanceMethod()));
        HPRTPrinterHelper.Form();
//        HPRTPrinterHelper.Print();
        HPRTPrinterHelper.PrintData("POPRINT\r\n");
    }

    private boolean ConnectDevice() {
        boolean bRet = false;
        myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        myBluetoothAdapter.cancelDiscovery();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            // 4.0.3版本 经测试，高版本兼容低版本
            mmDevice = myBluetoothAdapter.getRemoteDevice(SharedPreferencesUtils.getParameter(context, "SelectedTagMac"));
            if (Build.VERSION.SDK_INT < 15) {
                mmSocket = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
            } else {
                mmSocket = mmDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID);
            }
            myBluetoothAdapter.cancelDiscovery();
            Thread.sleep(100);
            if (myBluetoothAdapter.isDiscovering()) {
                int iCnt = 0;
                while (iCnt < 5) {
                    Thread.sleep(100);
                    iCnt++;
                    if (myBluetoothAdapter.cancelDiscovery()) {
                        break;
                    }
                }
            }
            mmSocket.connect();
        } catch (Exception e) {
            try {
                Method m;
                m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
                mmSocket = (BluetoothSocket) m.invoke(mmDevice, 1);
                if (myBluetoothAdapter.isDiscovering()) {
                    int iCnt = 0;
                    while (iCnt < 5) {
                        Thread.sleep(100);
                        iCnt++;
                        if (myBluetoothAdapter.cancelDiscovery()) {
                            break;
                        }
                    }
                }
                mmSocket.connect();
            } catch (Exception e1) {
                Log.d("PRTLIB", (new StringBuilder("BTO_ConnectDevice --> create ")).append(e1.getMessage()).toString());
                return false;
            }
        }

        try {
            bRet = GetIOInterface();
            return bRet;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private boolean GetIOInterface() {
        Log.d("PRTLIB", "BTO_GetIOInterface...");
        try {
            mmInStream = mmSocket.getInputStream();
            mmOutStream = mmSocket.getOutputStream();
        } catch (IOException e) {
            Log.d("PRTLIB", (new StringBuilder("BTO_GetIOInterface ")).append(e.getMessage()).toString());
            return false;
        }
        return true;
    }

    private InputStream mmInStream;
    private OutputStream mmOutStream;
    private BluetoothDevice mmDevice;
    private BluetoothSocket mmSocket;

    private boolean DisConnect() {
        boolean bRet = true;
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            if (mmInStream != null) {
                mmInStream.close();
                mmInStream = null;
            }
            if (mmOutStream != null) {
                mmOutStream.close();
                mmOutStream = null;
            }
            if (mmSocket != null) {
                mmSocket.close();
                mmSocket = null;
            }
        } catch (IOException e) {
            System.out.println((new StringBuilder("BTO_ConnectDevice close ")).append(e.getMessage()).toString());
            bRet = false;
        }
        return bRet;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.inject(this);
    }
}
